package com.api.shopapi.common;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;


/**
 * 主要实现文件上传，和接收方绑定接收后信息导入参数传递
 * @author zyb
 *
 */
public class HttpURLConnectionServices {

    private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private static final String PREFIX = "--";
    private static final String LINE_END = "\r\n";


    /**
     * @param fileName 要上传的文件，列：e:/upload/SSD4k对齐分区.zip
     * @param Url 上传路径端口号和项目名称，列：http://192.168.1.209:9080/gjbmj
     */
    public static void postFile(String fileKey,String fileName,String Url,Map<String,String> param){
        try {

            File file = new File(fileName);

            URL url = new URL(Url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(50000);
            conn.setConnectTimeout(50000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", "UTF-8"); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" +  BOUNDARY);

            /**
             * 当文件不为空，把文件包装并且上传
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = null;
            String params = "";


            /***
             * 以下是用于上传参数
             */
            if (param != null && param.size() > 0) {
                Iterator<String> it = param.keySet().iterator();
                while (it.hasNext()) {
                    sb = null;
                    sb = new StringBuffer();
                    String key = it.next();
                    String value = param.get(key);
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
                    sb.append(value).append(LINE_END);
                    params = sb.toString();
                    dos.write(params.getBytes());
                }
            }


            sb = null;
            params = null;
            sb = new StringBuffer();
            /**
             * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
             * filename是文件的名字，包含后缀名的 比如:abc.png
             */
            sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition:form-data; name=\""+fileKey+"\"; filename=\"" + file.getName() + "\"" + LINE_END);
            sb.append(LINE_END);
            params = sb.toString();
            sb = null;
            dos.write(params.getBytes());



            /**上传文件*/
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            int curLen = 0;
            while ((len = is.read(bytes)) != -1) {
                curLen += len;
                dos.write(bytes, 0, len);
            }
            is.close();


            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();




            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
            int res = conn.getResponseCode();
            if (res == 200) {
                BufferedReader reader=null;
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                StringBuffer sb1 = new StringBuffer();
                String ss;
                while((ss = reader.readLine())!=null){
                    sb1.append(ss);
                }
                System.out.println(sb1.toString());

                return;
            } else {
                return;
            }


        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //new File(fileName).delete();

            System.out.println("---over---");

        }
    }

}
